package middleware

import (
	"strconv"
	"time"
	"video-api/internal/consts"
	"video-api/utility/metrics"

	"github.com/gogf/gf/v2/net/ghttp"
)

// PrometheusMiddleware 中间件记录每个 HTTP 请求的耗时
func PrometheusMiddleware(r *ghttp.Request) {
	startTime := time.Now()
	// 执行下一步逻辑
	r.Middleware.Next()
	// 计算耗时
	duration := time.Since(startTime).Seconds()
	// 获取请求状态码
	statusCode := strconv.Itoa(r.Response.Status)
	// 获取用户信息
	info, exist := r.Context().Value(consts.USER_JWT_KEY).(*ClaimsInfo)
	var userId string
	if exist {
		userId = info.UserId
	}
	// 记录到 Prometheus
	metrics.HttpRequestDuration.WithLabelValues(r.Method, r.URL.Path, userId, statusCode).Observe(duration)
	//Summary类型
	metrics.HttpRequestDuration2.WithLabelValues(r.Method, r.URL.Path, userId, statusCode).Observe(duration)
	metrics.HttpRequestCounts.WithLabelValues(r.Method, r.URL.Path, statusCode).Inc()
}
